//
//  AppDelegate.m
//  test2
//
//  Created by TryHone on 16/7/13.
//  Copyright © 2016年 TryHone. All rights reserved.
//

#import "AppDelegate.h"
//#import <TKIMSDKUI/TKIMLoginViewController.h>
#import "TKIMLoginViewController.h"
//#import <TKIMSDKUI/TKIMRootViewController.h>
#import "TKIMRootViewController.h"
#import <AudioToolbox/AudioToolbox.h>
//#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()

@property(nonatomic, strong) TKIMLoginViewController *login;
@property(nonatomic, strong) UINavigationController *loginNav;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //登录界面
    _login = [[TKIMLoginViewController alloc] init];
    _loginNav = [[UINavigationController alloc] initWithRootViewController:_login];
    [_loginNav.navigationBar setTranslucent:NO];
    [_loginNav.navigationBar setBarTintColor:[UIColor blackColor]];

    NSDictionary *navTitleArr = [NSDictionary
      dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18],
                                   NSFontAttributeName, [UIColor whiteColor],
                                   NSForegroundColorAttributeName, nil];
    [_loginNav.navigationBar setTitleTextAttributes:navTitleArr];

    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.rootViewController = _loginNav;
    [_window makeKeyAndVisible];

    [[TKIMNotificationCenter shareInstance] start];
//    [TKIMSDKManager
//              start:APP_SDK_KEY
//            appType:SDKAPPTYPE_CUSTOMER
//      callBackBlock:^(NSInteger errorNumber, NSString *info) {
//        TKIMPrintInfo(@"Alan==%ld=%@====%@==%@=%@=%@", errorNumber, info,
//              [TKIMSDKManager imUDID], [TKIMSDKConfig shareInstance].generalUrl,
//              [TKIMCacheHelper valueForKey:TKIMHttpToken],
//              [TKIMSDKManager getLoginUserPuid]);
//      }];
    
    [[TKIMSDKConfig shareInstance] isYCP:NO];
    Class class = NSClassFromString(@"TKIMYCXmppDecoder");
    if (!class) {
        class = NSClassFromString(@"TKIMYCXmppDecoder");
    }
    [TKIMSDKConfig shareInstance].dataDecoder = class;
    [TKIMSDKManager start:APP_SDK_KEY appType:SDKAPPTYPE_CUSTOMER callBackBlock:^(NSInteger errorNumber, NSString *info) {
        TKIMPrintInfo(@"Alan==%ld=%@====%@==%@=%@=%@", errorNumber, info,
                      [TKIMSDKManager imUDID], [TKIMSDKConfig shareInstance].generalUrl,
                      [TKIMCacheHelper valueForKey:TKIMHttpToken],
                      [TKIMSDKManager getLoginUserPuid]);
    }];
    
  
    [[TKIMManager shareInstance] registerDelegate:self];
    [TKThemeManager shareInstance].theme = @"theme1";
  
//    Class class = NSClassFromString(@"TKIMYCXmppDecoder");
//    if (!class) {
//        class = NSClassFromString(@"TKIMYCXmppDecoder");
//    }
//    [TKIMSDKConfig shareInstance].dataDecoder = class;
    [[TKIMDBManager shareInstance] queryConverseTotal];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgCountChange:) name:SDK_MSGCOUNT_CHANGE object:nil];
    //UIViewController* rootViewControl = [[[[UIApplication sharedApplication] delegate] window] rootViewController;
    
    
    
    NSLog(@"register_message");
    
//    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//    if(userInfo  != nil){
//        TKIMPrintInfo(@"%@",@"UIApplicationLaunchOptionsRemoteNotificationKey is not nil");
//        [[TKIMNotificationCenter shareInstance]
//         didReceiveRemoteNotification:userInfo];
//
//        if (application.applicationState != UIApplicationStateActive) {
//            NSNotification *notice = [NSNotification notificationWithName:TKIMSDK_GO_H5
//                                                                   object:nil
//                                                                 userInfo:userInfo];
//            [[NSNotificationCenter defaultCenter] postNotification:notice];
//        }
//    }else{
//        TKIMPrintInfo(@"%@",@"UIApplicationLaunchOptionsRemoteNotificationKey is nil");
//    }
    return YES;
}

-(void)msgCountChange:(NSNotification *)no
{
    NSInteger total;
    if(no)
    {
        if(![no.object isEqualToString:@"query"])
            total = ((NSString *)no.userInfo).integerValue;
        else
            total = [[TKIMDBManager shareInstance] queryConverseTotal];
        
        NSLog(@"msgCountChange 1111 total = %l",total);
    }else{
        total = [[TKIMDBManager shareInstance] queryConverseTotal];
        NSLog(@"msgCountChange 2222 total = %l",total);
    }
}



- (void)didReceiveMessage:(TKIMMessage *)message
{
  if (message.isPoint) {
    AudioServicesPlaySystemSound(1004); //更换播放系统的声音 id值可以百度查询
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); //震动
  }
}


- (void)didReceiveServerStatus:(TKIMStatus *)status {
  NSLog(@"===");
  switch (status.statusCode) {
  case TKIMUserConflict: {
    [_loginNav popViewControllerAnimated:YES];
  } break;

  default:
    break;
  }
}

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  TKIMPrintInfo(@"%@", deviceToken.description);

  [[TKIMNotificationCenter shareInstance]
      didRegisterForRemoteNotification:deviceToken];
}

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo {
    TKIMPrintInfo(@"%@",@"didReceiveRemoteNotification");
  [[TKIMNotificationCenter shareInstance]
      didReceiveRemoteNotification:userInfo];

  if (application.applicationState != UIApplicationStateActive) {
    NSNotification *notice = [NSNotification notificationWithName:TKIMSDK_GO_H5 object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notice];
  }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    //
    TKIMPrintInfo(@"%@",@"didReceiveRemoteNotification");
    [[TKIMNotificationCenter shareInstance] didReceiveRemoteNotification:userInfo];
    
    if (application.applicationState != UIApplicationStateActive) {
        NSNotification *notice = [NSNotification notificationWithName:TKIMSDK_GO_H5 object:nil userInfo:userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
    }

}

- (void)application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  [[TKIMNotificationCenter shareInstance]
      didFailToRegisterForRemoteNotification:nil
                                       error:error];
}
- (void)application:(UIApplication *)application
    didReceiveLocalNotification:(UILocalNotification *)notification {
  [[TKIMNotificationCenter shareInstance]
      didReceiveLocalNotification:notification.userInfo];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
  // Called as part of the transition from the background to the inactive state;
  // here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  // Restart any tasks that were paused (or not yet started) while the
  // application was inactive. If the application was previously in the
  // background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
  // Called when the application is about to terminate. Save data if
  // appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationWillResignActive:(UIApplication *)application {
  // Sent when the application is about to move from active to inactive state.
  // This can occur for certain types of temporary interruptions (such as an
  // incoming phone call or SMS message) or when the user quits the application
  // and it begins the transition to the background state.
  // Use this method to pause ongoing tasks, disable timers, and throttle down
  // OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
  NSInteger total = [[TKIMDBManager shareInstance] queryConverseTotal];
  [[TKIMManager shareInstance]
      syncUserMsgCountToServer:total
                      callBack:^(TKIMResultVo *resultVo){
                      }];
  application.applicationIconBadgeNumber = total;
}
@end
